var userCache = {

	options: {
		success: function(data) {},
		error: function(error, thrown) {},
		loginUrl: 'login.html',
	},

	setOptions: function(userOptions) {
		console.log('设置属性', userOptions)
		Object.assign(this.options, userOptions)
	},

	setToken: function(token) {
		localStorage.setItem("token", token)
	},

	setDeviceNo: function(deviceNo) {
		localStorage.setItem("deviceNo", deviceNo)
	},

	setBaseUrl(ip) {
		let url = ip.indexOf("http://") == 0 ? ip : "http://" + ip
		localStorage.setItem("ip", url);
	},

	getBaseUrl() {
		let ip = localStorage.getItem("ip");
		let url = ip.indexOf("http://") == 0 ? ip : "http://" + ip
		return url;
	},

	getDeviceNo: function() {
		return localStorage.getItem("deviceNo")
	},

	removeDeviceNo: function() {
		localStorage.removeItem("deviceNo")
	},

	getUser: function() {
		let str = localStorage.getItem("user")
		if (str) {
			return JSON.parse(str)
		}
	},
	
	//返回登录页
	_gotoLogin: function(){
		let _self = this
		var curr = plus.webview.currentWebview();
		var wvs = plus.webview.all();
		//登录失效关闭所有页面
		for (var i = 0, len = wvs.length; i < len; i++) {
			//跳过当前页
			if (wvs[i].getURL() == curr.getURL())
				continue;
			plus.webview.close(wvs[i]);
		}
		//跳转登录页面
		if (_self.options.loginUrl) {
			plus.webview.open(_self.options.loginUrl);
		}
		//清空缓存
		localStorage.setItem("isLogin", false);
		localStorage.setItem("token", "");
		localStorage.setItem("userId", "");
		localStorage.setItem("user", "");
		curr.close()
	},

	getUserInfo: function() {
		let _self = this
		let ip = localStorage.getItem("ip");
		let token = localStorage.getItem("token");
		if(!token){
			_self._gotoLogin();
			return
		}
		mui.ajax(ip + '/getInfo', {
			dataType: 'json', //服务器返回json格式数据
			type: 'get', //HTTP请求类型
			timeout: 10000, //超时时间设置为10秒；
			headers: {
				'authorization': token
			},
			success: function(data) {
				localStorage.setItem("userId", data.user ? data.user.userId : null)
				if (data.code == 200) {
					let userObj = data.user
					localStorage.setItem("user", JSON.stringify(userObj))
					console.log('调用回调')
					_self.options.success(data)
				} else if (data.code == 401) {
					mui.toast("登录状态过期,请重新登陆")
					_self._gotoLogin();
				} else {
					//mui.toast("系统内部错误，请重新登录");
					console.log('系统内部错误', data.msg)
					_self.options.error('调用API发生业务异常', data)
				}
			},
			error: function(xhr, type, errorThrown) {
				console.error('调用API发生系统异常', type, errorThrown);
				mui.toast("系统内部错误");
				_self.options.error(type, errorThrown)
			}
		});
	}
}